package cn.xutongxue.doc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.xutongxue.common.enums.Errors;
import cn.xutongxue.common.utils.ThrowUtils;
import cn.xutongxue.doc.module.dto.DocUploadRequestDto;
import cn.xutongxue.doc.module.dto.DocUploadResultDto;
import cn.xutongxue.doc.module.vo.DocVo;
import cn.xutongxue.doc.utils.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.xutongxue.doc.entity.Doc;
import cn.xutongxue.doc.service.DocService;
import cn.xutongxue.doc.mapper.DocMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author PC
 * @description 针对表【doc(文档信息表)】的数据库操作Service实现
 * @createDate 2025-06-02 21:25:04
 */
@Service
public class DocServiceImpl extends ServiceImpl<DocMapper, Doc>
        implements DocService {


    @Resource
    private FileUtil fileUtil;

    @Override
    public DocVo uploadDoc(MultipartFile file, HttpServletRequest httpServletRequest, DocUploadRequestDto requestDto) {
        // 参数校验
        Integer currentUserId = StpUtil.getLoginIdAsInt();
        // 获取当前登录用户信息
        ThrowUtils.throwIf(file == null, Errors.PARAMS_ERROR);
        // 判断新增 or 删除
        Integer docId = null;
        if (requestDto != null) {
            docId = requestDto.getId();
        }
        // 如果是更新
        if (docId != null) {
            boolean exists = this.lambdaQuery()
                    .eq(Doc::getId, docId)
                    .exists();
            ThrowUtils.throwIf(!exists, Errors.ITEM_NOT_FOUND, "文档不存在");
        }
        // 上传文件 获取文件信息
        String uploadPathPrefix = String.format("public/%s", currentUserId);
        DocUploadResultDto docUploadResultDto = fileUtil.uploadDoc(file, uploadPathPrefix);

        // 保存文件信息
        Doc doc = new Doc();
        doc.setUrl(docUploadResultDto.getUrl());
        doc.setFilename(docUploadResultDto.getFilename());
        doc.setFileSize(docUploadResultDto.getFileSize());
        doc.setFileFormate(docUploadResultDto.getFileFormate());
        doc.setUserId(currentUserId);
        if (docId != null) {
            // 更新信息
            doc.setId(docId);
        }

        boolean result = this.saveOrUpdate(doc);
        ThrowUtils.throwIf(!result, Errors.OPERATION_FAILED, "文件上传失败, 数据库操作失败");
        DocVo DocVo = new DocVo();
        BeanUtil.copyProperties(doc, DocVo);
        return DocVo;
    }
}




